#!/bin/bash

project_dir=$(dirname $(dirname $(readlink -f "$0")))

exclude_dir=""
exclude_file=""

function process_item() {
    line="$1"
    path=$(echo "${line}" | tr -d "[:blank:]")
    if test -z ${path}; then
        return
    fi

    if test "${path:0:1}" == "#"; then
        return
    fi

    if test -d ${path}; then
        if test -z "${exclude_dir}"; then
            exclude_dir="-path ${project_dir}/${path}"
        else
            exclude_dir="${exclude_dir} -o -path ${project_dir}/${path}"
        fi
    else
        if test -z "${exclude_file}"; then
            exclude_file="-not -path  ${project_dir}/${path}"
        else
            exclude_file="${exclude_file} -a -not -path ${project_dir}/${path}"
        fi
    fi
}

while read line; do
    process_item "${line}"

done \
    <${project_dir}/.clang-tidy-ignore

if test -n ${line}; then
    process_item ${line}
fi

exclude_dir_optoins=""
if test -n "${exclude_dir}"; then
    exclude_dir_optoins="\( ${exclude_dir} \) -prune -o"
fi

exclude_file_optoins=""
if test -n "${exclude_file}"; then
    exclude_file_optoins="-a \( ${exclude_file} \)"
fi

# filelist=`find ${project_dir} \( ${exclude_dir} \) -prune  -o -type f -a \( -name "*.cc" -o -name "*.hpp" -o -name "*.h" -o -name "*.c" \) -a \( ${exclude_file} \) -print`
command="find ${project_dir}/src "${exclude_dir_optoins}" -type f \\( -name '*.cc' -o -name '*.hpp' -o -name '*.h' -o -name '*.c' \\) "${exclude_file_optoins}" -print"
echo ${command} >/tmp/findfiles_cmd.sh
filelist=$(cat /tmp/findfiles_cmd.sh | bash)
rm -rf /tmp/findfiles_cmd.sh

set -x
clang-tidy -p "${project_dir}" ${filelist}
set +x
